package com.example.test_bitmap

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.FileOutputStream

class MainActivity : AppCompatActivity() {
    companion object{
        private const val TAG = "MainActivity"
    }
    private lateinit var iv:ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        iv = findViewById(R.id.iv)
        //加载图片
//        val options = BitmapFactory.Options()
//        options.inPreferredConfig = Bitmap.Config.ARGB_8888 //像素格式 2个字节
//        val bitmap = BitmapFactory.decodeResource(resources,R.drawable.a,options)
//        Log.d(TAG, "onCreate:大小 "+bitmap.byteCount) //165375000  330750000

        //二次采样：
        //第一次：不采像素点，只采集原图的宽高--->计算压缩比例
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true //只采集宽和高
        BitmapFactory.decodeResource(resources,R.drawable.a,options)
        val height = options.outHeight
        val width = options.outWidth
        Log.d(TAG, "宽:$width 高：$height")
        //计算压缩比例：2的幂次方 2 4 8 16 32
        var inSampleSize = 1
        while (height / inSampleSize > 100  || width / inSampleSize > 80){
            inSampleSize *= 2
        }
        Log.d(TAG, "压缩比例: $inSampleSize")
        //第二次：采集像素点，按照压缩比例采集
        options.inJustDecodeBounds = false
        options.inSampleSize = inSampleSize //压缩比例
        options.inPreferredConfig = Bitmap.Config.ARGB_8888
        val bitmap = BitmapFactory.decodeResource(resources,R.drawable.a,options)
        iv.setImageBitmap(bitmap)
        Log.d(TAG, "大小: ${bitmap.byteCount}") //78892
        //质量压缩:png无损格式不受影响，jpg受影响
        Thread{
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,FileOutputStream("/sdcard/Pictures/a.jpg")) //18.6kb
            bitmap.compress(Bitmap.CompressFormat.JPEG,10,FileOutputStream("/sdcard/Pictures/b.jpg")) //2.1kb
        }.start()





    }
}